/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "DiagramNode.h"
#include "DiagramEdge.h"
#include "DiagramView.h"

namespace QSThink
{
	DiagramNode::DiagramNode( DiagramView *view,Transaction* trans )
		: _view(view),_trans(trans)
	{
		setFlag(ItemIsSelectable);//ItemIsMovable
		setFlag(ItemSendsGeometryChanges);
		setCacheMode(DeviceCoordinateCache);
		setAcceptHoverEvents(true);

		setZValue(0);
	}

	void DiagramNode::addEdge( DiagramEdge *edge )
	{
		_edgeList << edge;
		edge->adjust();
	}

	QList<DiagramEdge *> DiagramNode::edges() const
	{
		return _edgeList;

	}

	
	bool DiagramNode::advance()
	{
		if(_position==pos()){
			return false;
		}
		setPos(_position);
		return true;
	}

	QRectF DiagramNode::boundingRect() const
	{
		qreal adjust = 0;
		return QRectF(-2 - adjust, -2 - adjust,4 + adjust, 4 + adjust);

	}


	QPainterPath DiagramNode::shape() const
	{
		QPainterPath path;
		path.addEllipse(-2, -2, 4, 4);
		return path;
	}

	void DiagramNode::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
	{
		//shadow
		return;
		QRadialGradient gradient(-3,-3,10);
		if(option->state&QStyle::State_Sunken){
			gradient.setCenter(3,3);
			gradient.setFocalPoint(3,3);
			gradient.setColorAt(1,QColor(Qt::green).light(200));
			gradient.setColorAt(0,QColor(Qt::darkGray).light(200));

		}else{
			gradient.setColorAt(0,Qt::green);
			gradient.setColorAt(1,Qt::darkGray);

		}

		painter->setBrush(gradient);
		painter->setPen(QPen(Qt::black,0));
		painter->drawEllipse(-2,-2,4,4);
	}

	QVariant DiagramNode::itemChange( GraphicsItemChange change, const QVariant &value )
	{
		switch (change) {
		case ItemPositionHasChanged:
			foreach (DiagramEdge *edge, _edgeList){
				edge->adjust();
			}
			_view->itemMoved();
			break;
		default:
			break;
		}

		return QGraphicsItem::itemChange(change, value);


	}

	void DiagramNode::mousePressEvent( QGraphicsSceneMouseEvent *evt )
	{
		update();
		QGraphicsItem::mousePressEvent(evt);

	}

	void DiagramNode::mouseReleaseEvent( QGraphicsSceneMouseEvent *evt )
	{
		update();
		QGraphicsItem::mouseReleaseEvent(evt);

	}

	void DiagramNode::hoverEnterEvent( QGraphicsSceneHoverEvent * event )
	{
		this->setCursor(Qt::ArrowCursor);


		_view->OnEnterNode(this);

		QGraphicsItem::hoverEnterEvent(event);


	}
	void DiagramNode::hoverLeaveEvent( QGraphicsSceneHoverEvent * event )
	{
		this->setCursor(Qt::OpenHandCursor);


		_view->OnLeaveNode(this);
		QGraphicsItem::hoverLeaveEvent(event);

	}

	Transaction* DiagramNode::getTransaction()
	{
		return _trans;
	}

	DiagramNode::~DiagramNode()
	{
		
	}


}
